package second.codeTop.package2;

import util.ListNode;
import util.TreeNode;

import java.util.HashMap;

/**
 * @ClassName LC141
 * @description:
 * @author: 荣燊
 * @create: 2022-04-03 14:38
 **/
public class LC141 {
    public static void main(String[] args) {

    }

    // 判断链表是否有环
    // 方法一:哈希表法
    public static boolean hasCycle1(ListNode head) {
        HashMap<ListNode, Integer> hashMap = new HashMap<ListNode, Integer>();
        while (head != null) {
            if (hashMap.containsKey(head)) {
                return true;
            } else {
                hashMap.put(head, head.val);
                head = head.next;
            }
        }
        return false;
    }

    // 方法二：快慢指针法
    public static boolean hasCycle2(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }
}
